package com.zq.download;

import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import android.util.Log;

import com.zq.download.bean.DownloadInfo;
import com.zq.download.utils.DBUtils;
import com.zq.download.utils.DownloadUtils;
import com.zq.download.utils.MD5Utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by zhangqiang on 17-6-21.
 */

public class DownloadTask implements Runnable {

    private ExecutorService executorService = Executors.newCachedThreadPool();

    private String url;

    private String savePath;
    private SQLiteOpenHelper sqLiteOpenHelper;

    public DownloadTask(String url, int threadCount, String savePath, String partSavePath,SQLiteOpenHelper sqLiteOpenHelper) {
        this.url = url;
        this.savePath = savePath;
        this.sqLiteOpenHelper = sqLiteOpenHelper;
    }

    @Override
    public void run() {

        File dir = new File(savePath);
        if(!dir.exists() && !dir.mkdirs()){
            return;
        }

        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        try {
            HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
            int contentLength = urlConnection.getContentLength();
            String fileName = DownloadUtils.getFileName(urlConnection,url);

            File saveFile = new File(dir,fileName);

            String taskTag = getTaskTag(url,saveFile.getAbsolutePath());

            List<DownloadInfo> downloadInfoList = DBUtils.getDao(sqLiteOpenHelper,DownloadInfo.class).query("tag=?",new String[]{taskTag});
            if(downloadInfoList != null && !downloadInfoList.isEmpty()){

                DownloadInfo downloadInfo = downloadInfoList.get(0);
//                if(downloadInfo)
                return;
            }

            DownloadInfo downloadInfo = new DownloadInfo();
            downloadInfo.setUrl(url);
            downloadInfo.setSavePath(saveFile.getAbsolutePath());
            downloadInfo.setContentLength(contentLength);

            byte[] buffer = new byte[1024 * 4];
            bis = new BufferedInputStream(urlConnection.getInputStream());

            fos = new FileOutputStream(saveFile);
            int len;
            int downloadLength = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                downloadLength += len;
            }

            Log.i("Test","===========下载完成===");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){

        enqueue(this);
    }

    private void enqueue(Runnable runnable){

        executorService.submit(runnable);
    }

    private static String getFileName(URLConnection response, String url){

        final String FILE_NAME_PREFIX = "filename=";

        String content_disposition = response.getHeaderField("content-disposition");
        if(TextUtils.isEmpty(content_disposition)){
            return null;
        }
        String[] items = content_disposition.split(";");

        for (String item:
                items) {

            item = item.trim();
            if(item.startsWith(FILE_NAME_PREFIX)){

                return item.substring(FILE_NAME_PREFIX.length());
            }
        }
        return null;
    }


    private String getTaskTag(String url,String filePath){

        return MD5Utils.getStringMD5(url + filePath);
    }


}
